package com.example.myapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.example.myapp.robot.ChatAdapter;
import com.example.myapp.robot.ChatBean;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.tls.OkHostnameVerifier;

public class RobotActivity extends AppCompatActivity {

    private ListView listView;
    private ChatAdapter adapter;
    private List<ChatBean> chatBeanList;
    private EditText et_send_msg;
    private Button btn_send;
    private String sendMsg;
    private String welcome[];
    private MHandler mHandler;
    public static final int MSG_OK=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_robot);
        chatBeanList=new ArrayList<ChatBean>();
        mHandler=new MHandler();
        welcome=getResources().getStringArray(R.array.welcome);
        initView();
    }

    private void initView() {
        listView=(ListView) findViewById(R.id.list);
        et_send_msg=(EditText) findViewById(R.id.et_send_msg);
        btn_send=(Button) findViewById(R.id.btn_send);
        adapter=new ChatAdapter(chatBeanList,this);
        listView.setAdapter(adapter);
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendData();
            }
        });
        et_send_msg.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode==KeyEvent.KEYCODE_ENTER){
                    sendData();
                }
                return false;
            }
        });
    }
    private void sendData() {
        sendMsg=et_send_msg.getText().toString();
        if (TextUtils.isEmpty(sendMsg)){
            Toast.makeText(this,"您还未输入任何信息哦",Toast.LENGTH_LONG).show();
            return;
        }
        et_send_msg.setText("");
        sendMsg=sendMsg.replaceAll(" ","").replaceAll("\n","")
                .trim();
        ChatBean chatBean=new ChatBean();
        chatBean.setMessage(sendMsg);
        chatBean.setState(chatBean.SEND);
        chatBeanList.add(chatBean);
        adapter.notifyDataSetChanged();
        getDataFromServer();
    }

    private void getDataFromServer() {
        OkHttpClient okHttpClient=new OkHttpClient();
        Request request=new Request.Builder().url("http://api.qingyunke.com/api.php?key=free&appid=0&msg="+sendMsg).build();
        Call call =okHttpClient .newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String res= response.body().string();
                Message msg=new Message();
                msg.what=MSG_OK;
                msg.obj=res;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }
        });
    }
    class MHandler extends Handler{
        @Override
        public void dispatchMessage (Message msg){
            super.dispatchMessage(msg);
            switch (msg.what){
                case MSG_OK:
                    if(msg.obj !=null){
                        String vlResult = (String)msg.obj;
                        paresDate(vlResult);
                    }
                    break;
            }
        }
    }
    private void paresDate(String JsonDate){
        try {
            JSONObject obj =new JSONObject(JsonDate);
            String content =obj.getString("content");
            updateView(content);
        } catch (JSONException e){
            e.printStackTrace();
            showDate("主人，你的网络不好哦");
        }
    }

    private void showDate(String message){
        ChatBean chatBean = new ChatBean();
        chatBean.setMessage(message);
        chatBean.setState(chatBean.RECEIVE);
        chatBeanList.add(chatBean);
        adapter.notifyDataSetChanged();
    }
    private void updateView(String content){
                showDate(content);
    }
    protected long exitTime;
    @Override
    public  boolean onKeyDown(int keyCode,KeyEvent event){
        if(keyCode==KeyEvent.KEYCODE_BACK
                &&event.getAction()==KeyEvent.ACTION_DOWN){
            if ((System.currentTimeMillis()-exitTime)>2000){
                Toast.makeText(RobotActivity.this,"再按一次退出智能聊天程序",Toast
                                .LENGTH_SHORT).show();
                exitTime=System.currentTimeMillis();
            }else{
                RobotActivity.this.finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode,event);
    }
}